package tmproject.hlhj.fhp.tmvote.customView

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.view.LayoutInflater
import android.widget.LinearLayout
import android.widget.PopupWindow
import com.autonavi.ae.search.log.GLog.filename
import com.bumptech.glide.Glide
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import com.lzy.okrx.adapter.ObservableResponse
import kotlinx.android.synthetic.main.dialog_ewm.*
import kotlinx.android.synthetic.main.pop_ewm.view.*
import rx.schedulers.Schedulers
import tmproject.hlhj.fhp.tmvote.BaseAty
import tmproject.hlhj.fhp.tmvote.R
import tmproject.hlhj.fhp.tmvote.beans.BaseBean
import tmproject.hlhj.fhp.tmvote.network.BaseObersever
import tmproject.hlhj.fhp.tmvote.network.JsonConvert
import tmproject.hlhj.fhp.tmvote.network.Urls
import tmproject.hlhj.fhp.tmvote.utils.ToastUtil
import tmproject.hlhj.fhp.tmvote.utils.ZxingUtils
import java.io.File
import java.io.FileOutputStream

/**
 * Created by Never Fear   on 2018\8\16 0016.
Never More....
 */
class EwmPop(private val context: Context,private val imgUrl:String) :PopupWindow(context) {
    private  var mMediaonnection: MediaScannerConnection?=null
    private val PERMISSIONS : Array<String> = arrayOf("android.permission.READ_EXTERNAL_STORAGE","android.permission.WRITE_EXTERNAL_STORAGE")
    private var ewmBit:Bitmap?=null
    init {

        this.width=LinearLayout.LayoutParams.MATCH_PARENT
        this.height=LinearLayout.LayoutParams.MATCH_PARENT
        setPop()
    }

    private fun setPop() {

        contentView=LayoutInflater.from(context).inflate(R.layout.pop_ewm,null)
        ToastUtil.toast("请保存二维码后到微信或支付宝扫码相册支付！")
        val permission = ContextCompat.checkSelfPermission(context,
        "android.permission.WRITE_EXTERNAL_STORAGE");
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // 没有写的权限，去申请写的权限，会弹出对话框
            ActivityCompat.requestPermissions(context as Activity, PERMISSIONS,1);
        }

        OkGo.get<BaseBean>(Urls.Base_Url+ Urls.Ewm)
                .params("pay_sn",imgUrl)
                .converter(object : JsonConvert<BaseBean>(){})
                .adapt(ObservableResponse<BaseBean>())
                .subscribeOn(Schedulers.io())
                .subscribe(object : BaseObersever<Response<BaseBean>>(context){
                    override fun onRespSuccess(t: Response<BaseBean>) {
                        val baseBean = t.body()
                        ewmBit = ZxingUtils.createBitmap(baseBean.data.toString())
                        Glide.with(context)
                                .load(ewmBit)
                                .into(contentView.imgEwm)
                    }
                })

        contentView.btCancel.setOnClickListener {
            dismiss()
        }

        contentView.btSave.setOnClickListener {
            saveBitmap(ewmBit!!,"TM${System.currentTimeMillis()}")
        }


    }
    fun saveBitmap( bitmap:Bitmap, bitName:String){
        var fileName:String?=null ;
        var file:File?=null ;
        if(Build.BRAND .equals("Xiaomi") ){ // 小米手机
            fileName = Environment.getExternalStorageDirectory().getPath()+"/DCIM/Camera/"+bitName+".jpg" ;
        }else{  // Meizu 、Oppo
            fileName = Environment.getExternalStorageDirectory().getPath()+"/DCIM/"+bitName+".jpg" ;
        }
        file = File(fileName);
        file?.setReadable(true)
        if(file.exists()){
            file.delete();
        }
        val out :FileOutputStream?=null;
        try{
            val out = FileOutputStream(file);
            // 格式为 JPEG，照相机拍出的图片为JPEG格式的，PNG格式的不能显示在相册中
            if(bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out))
            {
                out.flush();
                out.close();
// 插入图库
                MediaStore.Images.Media.insertImage(context.contentResolver, file.getAbsolutePath(), bitName, null);
                ToastUtil.toast("保存成功")
                val baseAty = context as BaseAty<*, *>
                dismiss()
                baseAty.finish()
            }
        }
        catch ( e:Exception)
        {
            e.printStackTrace();
        }
        // 发送广播，通知刷新图库的显示
        context.sendBroadcast( Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + fileName)));
        try {
            mMediaonnection = MediaScannerConnection(context,  object :MediaScannerConnection.MediaScannerConnectionClient{
                override fun onMediaScannerConnected() {
                    mMediaonnection?.scanFile(Environment.getExternalStorageDirectory().getPath()+"/DCIM/",filename);
                }
                override fun onScanCompleted(path: String?, uri: Uri?) {
                    mMediaonnection?.disconnect();
                }
            })
            mMediaonnection!!.connect()
        }catch ( e:Exception){
        }
    }
}